<?php

namespace App\Service\UserService;

use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\PssModel\PddToken;
use App\Service\VendorClient\ShopXiaohongshuApi\ShopXiaohongshuApiClient;
use App\Model\PssModel\XiaoHongShuGoods;
use Hyperf\Utils\WaitGroup;
use App\Amqp\Producer\XiaohongshuMessageProducer;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Amqp\Producer;
use function GuzzleHttp\json_decode;

/**
 * 小红书服务中心
 * @author chenshubo
 */
class XHSService extends BaseService
{
    protected $XiaohongshuClient;
    protected $config;
    
    /**
     * 接收消息数据
     * @param string $messageType
     * @param array $data
     */
    public function MessageRev(string $messageType,array $data)
    {
        return $this->{$messageType}($data);
    }
    
    /**
     * 商品消息变化
     * @param array $data
     */
    public function goodsChange(array $data)
    {
        $config = $config = $this->getConfig();
        $this->XiaohongshuClient = new ShopXiaohongshuApiClient($config);
        //开启协程
        $count = count($data);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($data as $goods)
        {
            co(function () use ($wg,$goods,& $result_update)
            {
                $response = $this->syncSingleXiaoHongShuGoods($goods);
                $result_update[] = $response;
                $wg->done();
            });
        }
        $wg->wait();
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
    /**
     * 商品批量下架
     * @param array $data
     */
    public function goodsSkuChange(array $data)
    {
        $config = $this->getConfig();
        $this->XiaohongshuClient = new ShopXiaohongshuApiClient($config);
        $produts = XiaoHongShuGoods::instance()
        ->select(['item_id'])
        ->whereIn('skucode',$data['skuList'])
        ->whereNotNull('item_id')
        ->get()
        ->toArray();
        if( empty($produts) ) {
            return Normal::returnCode(Normal::SUC,"没有满足的数据，无须处理");
        }
        
        //开启协程
        $count = count($produts);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($produts as $item)
        {
            co(function () use ($wg,$item,& $result_update)
            {
                $response = $this->XiaohongshuClient->itemDelistUpdate($item["item_id"]);
                $result_update[] = $response;
                $wg->done();
            });
        }
        $wg->wait();
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
    /**
     * 商品全量下架
     * @param array $data
     */
    public function goodsBatchDown(array $data)
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
        $config = $this->getConfig();
        $this->XiaohongshuClient = new ShopXiaohongshuApiClient($config);

        //先查询出小红书的所有商品
        $page = 1;
        while (true)
        {
            $query = [
                'page'      => $page,
                'pageSize'  => "10",
            ];
            $result_item = $this->XiaohongshuClient->itemGet($query);
            //如果没有商品就暂停查询
            if ($result_item['code'] != Normal::SUC  || empty($result_item["data"]["item_list_get_response"]["items"]))
            {
                break;
            }
            $result_item = $result_item["data"]["item_list_get_response"]["items"];
            //开始协助并发下架商品
            $item_count = count($result_item);
            $wg = new WaitGroup();
            $wg->add($item_count);
            foreach ($result_item as $item)
            {
                $item_id  =$item["item_id"];
                co(function () use ($item_id,$wg) {
                    $this->XiaohongshuClient->itemDelistUpdate($item_id);
                    $wg->done();
                });
            }
            $wg->wait();
            $page++;
        }
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 同步商品
     * @param array $goods
     */
    public function syncSingleXiaoHongShuGoods(array $goodsInfo)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList     = current($skuInfo['storeList']);
        $batchFirst    = current($storeList['goods_batch_list']);
        $firstSpec     = current($batchFirst['spec_list']);
        $goodsSpecAttr = $goodsInfo["goodsSpecAttr"];
        
        //判断是否向小红书推送过商品，如果有，就执行更新操作，没有执行添加操作
        $XiaohongshuGood  = XiaoHongShuGoods::instance()->info(['skucode' => $skucode]);
        if( !empty($XiaohongshuGood['item_id']) && !empty($XiaohongshuGood['sku_id']) )
        {
            echo "更新";die;
//             return $this->goodsXiaoHongShuUpdate($goodsInfo,$XiaohongshuGood);
        }
        else
        {
            $return = $this->goodsXiaoHongShuAdd($goodsInfo,$XiaohongshuGood);
            return $return;
            if( $return['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"goodsXiaohongshuAdd接口查询失败【{$return['msg']}】",$return);
            }
            echo "新增";die;
           // return $this->goodsXiaoHongShuUpdate($goodsInfo,$return['data']['XiaohongshuGoods']);
        }
    }
    
    /**
     * 小红书更新
     * @param array $goods
     * @param array $XiaohongshuGood
     */
    public function goodsXiaoHongShuUpdate(array $goodsInfo,array $XiaohongshuGood)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList     = current($skuInfo['storeList']);
        $batchFirst    = current($storeList['goods_batch_list']);
        $firstSpec     = current($batchFirst['spec_list']);
        $goodsSpecAttr = $goodsInfo["goodsSpecAttr"];
        $sku_id         = $XiaohongshuGood["sku_id"];
        $item_id     = $XiaohongshuGood["item_id"];
        
        //进行批量调用接口
        $goodsUpdateAllItemList = [];
        
        //产品新增
        $goodsUpdateAllItemList[] = [
            'method'    => 'itemUpdate',
            'data'      => [
                "item_id"       => $item_id,
                "item_name"     => $goodsInfo["goodsName"],
                "item_desc"     => $goodsInfo["goodsName"],
                "third_item_id" => $skucode,
            ]
        ];
        
        //产品更新上架
        $goodsUpdateAllItemList[] = [
            'method'    => 'itemlistUpdate',
            'data'      => [
                "item_id" => $item_id,
            ]
        ];
        
        //产品详情更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'itemDetailUpdate',
            'data'      => [
                "item_id"    => $item_id,
                "detail[text]"  => $goodsInfo["description"],
            ]
        ];
        
        //sku价格更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'skuUpdate',
            'data'      => [
                "sku_id"        => $sku_id,
                "third_sku_id"  => $skucode,
                "amount"        => $firstSpec['priceSettlement'], //sku 结算价
                "mart_amount"   => $firstSpec['priceMarket'], //sku 原价，单位元，小数点最多保留 2 位
            ]
        ];
        
        //sku库存更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'skuQuantityUpdate',
            'data'      => [
                "sku_id"        => $sku_id,
                "num"           => $batchFirst["num"],
            ]
        ];
        
        //sku详情更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'skuDetailUpdate',
            'data'      => [
                "sku_id"        => $sku_id,
                "description"   => $goodsInfo["description"],
            ]
        ];
        
        //开启协程
        $count = count($goodsUpdateAllItemList);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($goodsUpdateAllItemList as $item)
        {
            co(function () use ($wg,$item,& $result_update)
            {
                $response = $this->XiaohongshuClient->{$item['method']}($item['data']);
                $result_update[] = [
                    'method'    => $item['method'],
                    'response'  => $response
                ];
                $wg->done();
            });
        }
        $wg->wait();
        $contents = [
            'item_id' => $item_id,
            'sku_id'     => $sku_id,
            'images'     => $goodsInfo['images']
        ];
        $message = new XiaohongshuMessageProducer($contents);
        $producer = ApplicationContext::getContainer()->get(Producer::class);
        $producer->produce($message);
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
//     /**
//      * 处理单个商品同步
//      * @param string $item_id
//      * @param array $item_id
//      */
//     public function uploadSingleitemImageByitemID(string $item_id,string $sku_id,array $images)
//     {
//         $this->config = $config = $this->getConfig();
//         $this->XiaohongshuClient = new ShopXiaohongshuApiClient($config);
//         //查询商品详情
//         $result_item = $this->XiaohongshuClient->itemQuery([
//             'item_id'    => $item_id
//         ]);
//         if( $result_item['code'] != Normal::SUC ) {
//             return Normal::returnCode(Normal::FAIL,"itemQuery接口查询失败【{$result_item['msg']}】",$result_item);
//         }
        
//         //获取图片，删除数据
//         $pic_ids = [];
//         if( !empty($result_item['data']['item_detail_get_response']['item']['pic_list']) ) {
//             $pic_list = $result_item['data']['item_detail_get_response']['item']['pic_list'];
//             $pic_ids  = array_column($pic_list,'pic_id');
//         }
        
//         if( !empty($pic_ids) ) {
//             $result_item_image_delete = $this->XiaohongshuClient->itemImageDelete([
//                 'item_id'    => $item_id,
//                 'pic_ids'       => \implode(",", $pic_ids)
//             ]);
//             if( $result_item_image_delete['code'] != Normal::SUC ) {
//                 return Normal::returnCode(Normal::FAIL,"itemQuery接口查询失败【{$result_item_image_delete['msg']}】",$result_item_image_delete);
//             }
//         }
        
//         //循环一个个得上传更新图片
//         $result_all = [];
//         foreach ($images as $imageUrl)
//         {
//             $result_all[] = $this->XiaohongshuClient->itemImageUpload([
//                 "item_id"    => $item_id,
//                 "image"         => $imageUrl,
//             ]);
//         }
//         //更新列表页图片
//         $sku_image    = $images[0];
//         if($sku_image){
//             $result_all[] = $this->XiaohongshuClient->skuImageUpload([
//                 "sku_id"    => $sku_id,
//                 "image"     => $sku_image,
//             ]);
//         }
//         return Normal::returnCode(Normal::SUC,"处理完成",$result_all);
//     }
    
    
    /**
     * 小红书商品新增
     * @param array $goods
     * @param array $XiaohongshuGood
     */
    public function goodsXiaoHongShuAdd(array $goodsInfo,array $XiaohongshuGood)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList      = current($skuInfo['storeList']);
        $batchFirst     = current($storeList['goods_batch_list']);
        $firstSpec      = current($batchFirst['spec_list']);
        $goodsSpecAttr  = $goodsInfo["goodsSpecAttr"];
       // $result = $this->XiaohongshuClient->CategoryGet();
       // $result = $this->XiaohongshuClient->BrandGet();
       // $result = $this->XiaohongshuClient->TemplateListGet();
//         $result = $this->XiaohongshuClient->AttributeGet();
        $result = $this->XiaohongshuClient->MaterialUpload($goodsInfo);
        return $result;
        
        //查询商品是否添加过
        if( empty($XiaohongshuGood) || empty($XiaohongshuGood['item_id']) )
        {
            $pushData = [
                "name"                  => $goodsInfo["goodsName"],
                "images"                => [$goodsInfo["images"][0]],
                "imageDescriptions"     => $goodsInfo["images"],
            ];
            $result_itemAdd = $this->XiaohongshuClient->itemAdd($pushData);
            if( $result_itemAdd['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"itemAdd fail【{$result_itemAdd['msg']}】",$result_itemAdd);
            }
            
            $item_id = $result_itemAdd['data']['item_add_response']['item']['item_id'];
            if( empty($XiaohongshuGood) ) {
                XiaoHongShuGoods::instance()->add([
                    'skucode'    => $skucode,
                    'item_id' => $item_id,
                    'cd'         => time(),
                ]);
            } else {
                XiaoHongShuGoods::instance()->where('skucode',$skucode)->update([
                    'item_id'    =>  $item_id,
                    'md'            => time(),
                ]);                
            }
        } else {
            $item_id = $XiaohongshuGood['item_id'];
        }
        die;
        //添加sku数据        
        if( empty($XiaohongshuGood['sku_id']) ) 
        {
            $skuData = [
                "item_id"    => $item_id,
                "third_sku_id"  => $skucode,
                "sku_num"       => $batchFirst['num'], //sku 库存
                "amount"        => $firstSpec['priceSettlement'], //sku 结算价
                "mart_amount"   => $firstSpec['priceMarket'], //sku 原价，单位元，小数点最多保留 2 位
            ];
            $result_sku_add = $this->XiaohongshuClient->skuAdd($skuData);
            if( $result_sku_add['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"skuAdd fail【{$result_sku_add['msg']}】",$result_sku_add);
            }
            
            $sku_id = $result_sku_add['data']['sku_add_response']['item']['sku_id'];
            XiaoHongShuGoods::instance()->where('skucode',$skucode)->update([
                'sku_id'    => $sku_id,
                'md'        => time()
            ]);
        } else {
            $sku_id = $XiaohongshuGood['sku_id'];
        }
        return Normal::returnCode(Normal::SUC,"处理完成",[
            'XiaohongshuGoods'  => [
                'skucode'       => $skucode,
                'item_id'       => $item_id,
                'sku_id'        => $sku_id,
            ]
        ]);
    }
    
    private function getConfig()
    {
        $config = PddToken::instance()->info(['auth_type'=>PddToken::AUTH_TYPE_XIAOHONGSHU]);
        return $config;
    }
}